import Header from '../../components/Header/Header.vue';
import SideMenu from '../../components/SideMenu/SideMenu.vue';
import ApiInfoForm from '../../components/Form/ApiInfoForm.vue';
import TableAll from '../../components/Table/Table-all.vue';
import eventBus from '../../lib/eventBus';
import { operateParams } from '../../lib/utils';

export default {
    name: 'ApiList',
    components: {
        'ivu-header': Header,
        'ivu-sidemenu': SideMenu,
        'ivu-apiinfoform': ApiInfoForm,
        'table-all': TableAll,
    },
    data() {
        return {
            isLoading: false,
            isExpanding: false,
            isEditing: false,
            bizId: '',
            projId: '123',
            headerOption: {
                searchBar: {
                    isShow: true,
                    ajaxOption: {
                        url: '/api/api/search',
                        params: {
                            bizId: this.bizId,
                            projId: this.projId,
                        },
                    },
                },
                isScrolling: false,
            },
            menuData: [],
            // 当前的moduleName
            moduleName: '',
            apiDetail: {},
            // 接口修改信息
            apiEditInfo: {
                apiId: null,
                // author: this.$userInfo.username
            },
        };
    },
    created() {
        this.initPage();

        eventBus.$on('deleteParams', (paramInfo) => {
            const paramType = paramInfo.type === 1 ? 'requestParams' : 'responseParams';
            operateParams(this.apiDetail[paramType], 'delete', paramInfo.trId);
        });

        eventBus.$on('addSubParams', (paramInfo) => {
            const paramType = paramInfo.type === 1 ? 'requestParams' : 'responseParams';
            operateParams(this.apiDetail[paramType], 'add', paramInfo.trId);
        });
    },
    mounted() {
        const apiContentInner = document.getElementById('apiContentInner');

        apiContentInner.addEventListener('scroll', () => {
            this.scrollPage(apiContentInner.scrollTop > 5);
        });
    },
    methods: {
        /**
         * initPage 页面初始化
         */
        initPage() {
            this.ajaxGetProjectDetail(() => {
                const apiId = this.menuData[0].apiList[0].apiId;
                this.ajaxGetApiDetail(apiId);
            });
        },
        /**
         * flexContentArea 伸缩接口的编辑展示区域
         */
        flexContentArea() {
            this.isExpanding = !this.isExpanding;
        },

        ajaxGetProjectDetail(successCb) {
            this.Ajax({
                url: '/api/project/detail',
                params: {
                    bizId: this.bizId,
                    projId: this.projId,
                },
            })
            .then((res) => {
                const moduleList = res.data.data.moduleList;

                this.moduleName = moduleList[0].moduleName;
                this.menuData = moduleList;

                successCb && successCb();
            });
        },

        ajaxGetApiDetail(apiId) {
            this.isLoading = true;

            if (apiId !== undefined) {
                sessionStorage.setItem('apiId', apiId);
            }

            this.Ajax({
                url: '/api/api/detail',
                params: {
                    apiId: apiId || sessionStorage.getItem('apiId'),
                },
            })
            .then((res) => {
                this.apiDetail = res.data.data;
                this.isLoading = false;
            });
        },

        ajaxEditApi() {
            this.isLoading = true;

            this.apiEditInfo.apiDetail = this.apiDetail;
            this.apiEditInfo.time = +new Date();

            this.Ajax({
                // method: 'post',
                url: '/api/api/edit',
                params: this.apiEditInfo,
            })
            .then((res) => {
                this.isLoading = false;
            });
        },

        ajaxDiscardApi(apiId, successCb) {
            this.isLoading = true;

            this.Ajax({
                // method: 'post',
                url: '/api/api/discard',
                params: {
                    apiId,
                },
            })
            .then((res) => {
                this.isLoading = false;
                successCb && successCb();
            });
        },

        ajaxDeleteApi(apiId, successCb) {
            this.isLoading = true;

            this.Ajax({
                // method: 'post',
                url: '/api/api/delete',
                params: {
                    apiId,
                },
            })
            .then((res) => {
                this.isLoading = false;
                successCb && successCb();
            });
        },

        scrollPage(isScrolling) {
            this.headerOption.isScrolling = isScrolling;
        },

        /**
         * selectApi 菜单选择api
         * @param  {object} apiInfo 选中的api的信息
         */
        selectApi(apiInfo) {
            this.moduleName = apiInfo.moduleName;
            this.ajaxGetApiDetail(apiInfo.apiId);
        },

        /**
         * addNewApi 在当前模块下新增接口
         */
        addNewApi() {
            this.isEditing = true;
            this.apiDetail = {
                requestParams: [],
                responseParams: [],
            };
        },

        goEditing() {
            this.isEditing = true;
        },

        /**
         * cancelEditing 取消接口编辑
         */
        cancelEditing() {
            this.$Modal.confirm({
                content: '确认取消编辑？',
                onOk: () => {
                    // 刷新，重置当前接口信息
                    this.ajaxGetApiDetail();
                    this.isEditing = false;
                },
            });
        },

        /**
         * finishEditing 完成接口编辑
         */
        finishEditing() {
            // 新增接口
            if (!this.apiEditInfo.apiId) {
                this.$Modal.confirm({
                    content: '确认保存',
                    onOk: () => {
                        // 刷新，重置当前接口信息
                        this.ajaxEditApi();
                        this.isEditing = false;
                    },
                });
                return;
            }

            // 修改接口
            this.$Modal.confirm({
                title: '修改备注',
                render: (h) => {
                    return h('Input', {
                        props: {
                            value: this.apiEditInfo.reason,
                            autofocus: true,
                            placeholder: '请输入修改备注',
                        },
                        on: {
                            input: (val) => {
                                this.apiEditInfo.reason = val;
                            },
                        }
                    })
                },
                okText: '确认保存',
                onOk: () => {
                    // 提交接口修改信息
                    this.ajaxEditApi();
                    this.isEditing = false;
                },
            });
        },

        discardApi(apiId) {
            this.$Modal.confirm({
                title: "确认废弃接口",
                content: '接口废弃后可以查看但不能编辑，废弃操作不可恢复',
                onOk: () => {
                    this.ajaxDiscardApi(apiId, () => {
                        this.ajaxGetApiDetail(apiId);
                    });
                },
            });
        },

        deleteApi(apiId) {
            this.$Modal.confirm({
                title: "确认删除接口",
                content: '接口删除后不可以查看，删除操作不可恢复',
                onOk: () => {
                    this.ajaxDeleteApi(apiId, () => {
                        this.initPage();
                    });
                },
            });
        },

        mockApi() {
            this.$Message.error({
                content: 'mock功能暂未开放',
            });
        },

        /**
         * testApi 测试接口的返回参数是否符合要求
         */
        testApi() {
            this.$Message.error({
                content: '功能暂未开放',
            });
        },

        /**
         * addParam 添加参数
         * @param {number} type 参数表格类型
         */
        addParam(type) {
            // 数据驱动dom变动
            const paramType = type === 1 ? 'requestParams' : 'responseParams';
            operateParams(this.apiDetail[paramType], 'add');
        },
    },
    watch: {
        isLoading(newVal) {
            if (newVal) {
                this.$Spin.show();
            } else {
                this.$Spin.hide();
            }
        },
    },
};
